using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using SimpleOrmCFPC.Core.Model;
using SimpleOrmCFPC.Core.Query.Requests;
using SimpleOrmCFPC.Core.Query.Where;
using SimpleOrmCFPC.Core.Query.expressions.RequestBuilder.WhereElmentsBuilder.Helpers;

namespace SimpleOrmCFPC.Core.Query.expressions.ExprssionCompilers
{
    public class MemberWhereElementBuilder : IWhereElementBuilder
    {
        public IWhereElement Compute(Expression expression)
        {
            var mem = (MemberExpression)expression;
            object obj = null;

            if (IsFromParameter(mem))
            {
                return LastMemberOfExpression(mem);
            }
            else
            {
                var objectMember = Expression.Convert(expression, typeof(object));

                var getterLambda = Expression.Lambda<Func<object>>(objectMember);

                var getter = getterLambda.Compile();

                return new ConstantWhereElement(getter());
            }
        }

        private IWhereElement LastMemberOfExpression(MemberExpression mem)
        {
            if (mem == null)
                throw new Exception();
            //if (mem.Expression.NodeType == ExpressionType.MemberAccess)
            //    return LastMemberOfExpression(mem.Expression as MemberExpression);
            return CreateCompileResultFromColumn(mem);
        }

        private bool IsFromParameter(MemberExpression mem)
        {
            if (mem == null)
                return false;
            if (mem.Expression.NodeType == ExpressionType.Parameter)
                return true;
            if (mem.Expression.NodeType == ExpressionType.MemberAccess)
                return IsFromParameter(mem.Expression as MemberExpression);
            return false;
        }

        public void FillAdditionalInformation(Expression expression, SQLRequest request)
        {
            
        }


        private static IWhereElement CreateCompileResultFromColumn(MemberExpression mem)
        {
            return new SimpleWhereElement(mem.Expression.Type.GetEntityName() + "." + mem.Member.Name, new List<object>());
        }
    }
}